﻿# -*- coding: utf-8 *-*
import sys, smtplib, MimeWriter, base64, StringIO, os, string, time

from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders

def send_mail(send_from, send_to, subject, text, files=[],server="localhost", user = None, password = None):
 
    assert type(send_to)==list
    assert type(files)==list

    msg = MIMEMultipart()
    msg['From'] = send_from
    msg['To'] = COMMASPACE.join(send_to)
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = subject

    msgText = MIMEText(text, 'html', 'utf-8')
    msg.attach(msgText)

    for file in files:
        part = MIMEBase('application', "octet-stream")
        part.set_payload( open(file,"rb").read() )
        Encoders.encode_base64(part)
        part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file))
        msg.attach(part)

    smtp = smtplib.SMTP(server)
    if (user != None):
        smtp.ehlo()
        smtp_userid64 = base64.encodestring(user)
        smtp.docmd("auth", "login " + smtp_userid64[:-1])
    if password != None:
        smtp_pass64 = base64.encodestring(password)
        smtp.docmd(smtp_pass64[:-1])

    smtp.sendmail(send_from, send_to, msg.as_string())
    smtp.close()
